const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const serverRender = require('./server-render');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const development = process.env.NODE_ENV === 'development';

if(!development) {
  const serverEntry = require('../dist/server-entry').default;
  const template = fs.readFileSync(path.join(__dirname, '../dist/server.ejs'), 'utf8');
  app.use('/public', express.static(path.join(__dirname, '../dist')));
  app.get('*', (req, res) => {
    serverRender(serverEntry, template, req, res).catch(next);
  })
} else {
  const devServer = require('./server.dev');
  devServer(app);
}

app.use(function(error, req, res, next) {
  console.log(error);
  res.status(500).send(error);
})

app.listen(7001, () => {
  console.log('Success start server');
})